﻿using Entity;
using IService;
using Microsoft.AspNetCore.Mvc;
using Service;
using XingWeiDaWMSProject.Models;

namespace XingWeiDaWMSProject.Controllers
{
    public class OutboundManagementController : Controller
    {
        private readonly IInventoryService _inventoryService;
        private readonly IOutboundManagementService _outboundManagementService;

        public OutboundManagementController(IInventoryService inventoryService,IOutboundManagementService outboundManagementService)
        {
            _inventoryService = inventoryService;
            _outboundManagementService = outboundManagementService;
        }
        public IActionResult Index()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }


        public IActionResult Add()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        // 仓库列表查询接口（供前端调用）
        [HttpGet] // 接口路径：api/Warehouse/GetAllWarehouses
        public async Task<IActionResult> GetAllWarehouses()
        {
            try
            {
                // 调用你已写好的 GetAllAsync 方法，获取未删除的仓库列表
                List<WarehouseEntity> warehouses = await _inventoryService.GetAllWarehousesAsync();

                // 返回成功结果（前端可直接解析数据）
                return Ok(new
                {
                    success = true,
                    data = warehouses
                });
            }
            catch (Exception ex)
            {
                // 异常处理，返回错误信息
                return Ok(new
                {
                    success = false,
                    message = "查询仓库失败：" + ex.Message
                });
            }
        }


        //出库管理新增关联单号分页查询功能
        [HttpGet]
        public async Task<IActionResult> GetPagedOutbound(
           string sales_order_no = null,
           string document_status = null,
           string customer_name = null,
           DateTime? sales_date = null,
            string sales_person = null,
            string sales_dept = null,
           int currentPage = 1,
           int pageSize = 2)
        {
            try
            {
                var result = await _outboundManagementService.GetAllWMSOutboundAsync(
                    sales_order_no, document_status, customer_name, sales_date, sales_person, sales_dept, currentPage, pageSize);
                // 返回规范格式（前端可直接解析）
                return Json(new
                {
                    success = true,
                    data = result.items,  // 当前页数据
                    total = result.total, // 总条数
                    message = "查询成功"
                });

            }
            catch (Exception ex)
            {
                // 输出异常详情到日志（建议结合日志框架如Serilog/NLog）
                Console.WriteLine($"查询出库管理分页数据异常：{ex.Message}\n{ex.StackTrace}");
                // 返回友好的错误提示
                return StatusCode(500, new { Message = "服务器处理请求时发生异常，请联系管理员", ErrorDetail = ex.Message });
            }
        }


        /// <summary>
        /// 根据销售单号查询货品明细
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetBySalesOrderNo(string salesOrderNo)
        {
      
            // 2. 查询货品明细
            var details = await _outboundManagementService.GetOutboundById(salesOrderNo);
            return Ok(details);
        }




        /// <summary>
        /// 根据仓库ID查询库位（适配前端下拉框格式）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetLocationByWarehouseId(int warehouseId)
        {
            var locationList = await _outboundManagementService.GetByWarehouseId(warehouseId);
            // 转换为前端Element-Select需要的{label, value}格式
            var options = locationList.Select(loc => new
            {
                label = loc.location_name, // 库位编号+名称拼接显示
                value = loc.location_id.ToString() // 库位ID作为值（与前端v-model对应）
            }).ToList();
            return Ok(options);
        }

        /// <summary>
        /// 根据库位ID查询当前库存
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetInventoryByLocationId(int locationId)
        {
            var inventory = await _outboundManagementService.GetByLocationAndProduct(locationId);
            return Ok(inventory); // 直接返回库存数量（无数据返回0，服务层已处理）
        }


        //根据库位ID，仓库id，货品编号查询当前库存
        [HttpGet]
        public async Task<IActionResult> GetInventoryByTargetSql(int warehouseId, int locationId,string productCode)
        {
            var inventory = await _outboundManagementService.GetInventoryByTargetSql(warehouseId, locationId, productCode);
            return Ok(inventory);
        }



        [HttpPost]
        public async Task<IActionResult> AddOutboundOrder([FromBody] OutboundOrderRequest request)
        {
            try
            {
                // 前端验证：确保明细不为空
                if (request.Details == null || request.Details.Count == 0)
                {
                    return BadRequest(new { success = false, message = "请添加至少一条货品明细" });
                }

                // 调用服务层方法（内部处理事务和数据组装）
                int orderId = await _outboundManagementService.AddOutboundOrderAsync(
                    request.Order,    // 主表数据
                    request.Details   // 明细数据
                );

                return Ok(new { success = true, message = "出库单及明细新增成功", orderId });
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = ex.Message });
            }
        }






        /// <summary>
        /// 分页查询出库单
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetPagedOutboundOrders(
            string outboundOrderNo = null,
            string outboundType = null,
            string outboundStatus = null,
            string warehouseName = null,
            int currentPage = 1,
            int pageSize = 10)
        {
            try
            {
                // 调用服务层获取分页数据
                var paginationResult = await _outboundManagementService.GetOutboundOrders(
                    outboundOrderNo,
                    outboundType,
                    outboundStatus,
                    warehouseName,
                    currentPage,
                    pageSize);

                // 返回规范格式（与GetCustomerPage2保持一致，方便前端统一解析）
                return Json(new
                {
                    success = true,
                    data = paginationResult.items,  // 当前页数据（出库单列表）
                    total = paginationResult.total, // 总数据条数
                    message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                // 异常时返回错误信息
                return Json(new
                {
                    success = false,
                    data = new List<OutboundOrderDTO>(), // 空列表避免前端解析报错
                    total = 0,
                    message = $"查询失败：{ex.Message}"
                });
            }
        }










        /// <summary>
        /// 批量审核出库单
        /// </summary>
        /// <param name="dto">审核参数（与前端提交参数对应）</param>
        /// <returns>审核结果（匿名对象，包含success和message）</returns>
        [HttpPost]
        public async Task<IActionResult> AuditOutboundOrders([FromBody] OutboundAuditDTO dto)
        {
            try
            {
                // 1. 基础参数校验
                if (dto.ordernos == null || !dto.ordernos.Any())
                {
                    // 返回失败的匿名对象（与前端预期的{success, message}结构一致）
                    return Ok(new { success = false, message = "请选择需要审核的出库单" });
                }
                if (string.IsNullOrWhiteSpace(dto.audit_result))
                {
                    return Ok(new { success = false, message = "请选择审核结果" });
                }
                if (string.IsNullOrWhiteSpace(dto.reviewer))
                {
                    return Ok(new { success = false, message = "审核人不能为空" });
                }

                // 2. 调用服务层核心审核方法（包含事务）
                await _outboundManagementService.AuditAsync(dto);

                // 3. 审核成功返回
                return Ok(new { success = true, message = "审核成功" });
            }
            catch (Exception ex)
            {
                // 4. 捕获异常并返回错误信息
                return Ok(new { success = false, message = $"审核失败：{ex.Message}" });
            }
        }



    }
}
